package one.time.pad;

/*
 * Object that takes an 80x50 character message and encrypts or decrypts it
 */
public class cipher {
	private final int row,col,shiftVal,charSetSize;
	
	public cipher() {
		row = 50;
		col = 80;
		shiftVal = 32;
		charSetSize = 128 - shiftVal;
	}
	
	/*
	 * takes a message and a key (both 80x50 2d arrays), and returns an encrypted
	 * 2d array of the same size
	 */
	public char[][] encrypt(char[][] message, char[][] key) {
		char[][] toReturn = new char[col][row];
		for (int colCount = 0; colCount < col; colCount++) {
			for (int rowCount = 0; rowCount < row; rowCount++) {
				int a, b; // store the values temporarily to use for encrypting
				
				// for the message shift the ascii values to the printable chars
				if (message[colCount][rowCount] >= shiftVal) { 
					a = message[colCount][rowCount] - shiftVal;
				} else { // make unreadable chars the space char
					a = 0;
				}
				
				// for the key shift the ascii values to the printable chars
				if (key[colCount][rowCount] >= shiftVal) { 
					b = key[colCount][rowCount] - shiftVal;
				} else { // make unreadable chars the space char
					b = 0;
				}
				
				toReturn[colCount][rowCount] = (char)((a + b) % charSetSize + shiftVal); // does the actual encryption
			}
		}
		return toReturn; // returns the encrypted array
	}
	
	/*
	 * takes a message and a key (both 80x50 2d arrays), and returns an unencrypted
	 * 2d array of the same size
	 */
	public char[][] decrypt(char[][] message, char[][] key) {
		char[][] toReturn = new char[col][row];
		for (int colCount = 0; colCount < col; colCount++) {
			for (int rowCount = 0; rowCount < row; rowCount++) {
				int a, b; // store the values temporarily to use for encrypting
				
				// for the message shift the ascii values to the printable chars
				if (message[colCount][rowCount] >= shiftVal) { 
					a = message[colCount][rowCount] - shiftVal;
				} else { // make unreadable chars the space char
					a = 0;
				}
				
				// for the key shift the ascii values to the printable chars
				if (key[colCount][rowCount] >= shiftVal) { 
					b = key[colCount][rowCount] - shiftVal;
				} else { // make unreadable chars the space char
					b = 0;
				}
				
				toReturn[colCount][rowCount] = (char)((a - b) % charSetSize + shiftVal); // does the actual decryption and shifts back
			}
		}
		return toReturn; // returns the decrypted array
	}
}
